#include "libs/httplib.h"
#include "libs/json.hpp"
#include <atomic>
#include <chrono>
#include <random>
#include <string>
#include <thread>
#include <vector>

using json = nlohmann::json;
using namespace httplib;

// 服务状态枚举
enum class ServiceStatus
{
    Stopped,
    Running,
    Starting,
    Stopping,
    Error
};

// 服务信息结构
struct Service
{
    std::string id;
    std::string name;
    std::string description;
    ServiceStatus status;
    std::string lastUpdated;
};

// 模拟服务数据
std::vector<Service> services = {
    {"service1", "Web Server", "Nginx Web Server", ServiceStatus::Running, "2025-05-18 10:30:00"},
    {"service2", "Database", "MySQL Database", ServiceStatus::Running, "2025-05-18 10:25:00"},
    {"service3", "Cache", "Redis Cache", ServiceStatus::Stopped, "2025-05-18 09:45:00"}};

// 转换服务状态为字符串
std::string statusToString(ServiceStatus status)
{
    switch (status)
    {
    case ServiceStatus::Stopped:
        return "Stopped";
    case ServiceStatus::Running:
        return "Running";
    case ServiceStatus::Starting:
        return "Starting";
    case ServiceStatus::Stopping:
        return "Stopping";
    case ServiceStatus::Error:
        return "Error";
    default:
        return "Unknown";
    }
}

// 生成唯一ID
std::string generateId()
{
    static std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_int_distribution<> dis(1000, 9999);
    return "service" + std::to_string(dis(gen));
}

// 获取当前时间字符串
std::string getCurrentTime()
{
    auto now = std::chrono::system_clock::now();
    auto now_c = std::chrono::system_clock::to_time_t(now);
    std::string timeStr = std::ctime(&now_c);
    // 移除换行符
    if (!timeStr.empty() && timeStr[timeStr.length() - 1] == '\n')
    {
        timeStr.erase(timeStr.length() - 1);
    }
    return timeStr;
}

// 将服务转换为JSON
json serviceToJson(const Service &service)
{
    return {
        {"id", service.id},
        {"name", service.name},
        {"description", service.description},
        {"status", statusToString(service.status)},
        {"lastUpdated", service.lastUpdated}};
}

// 模拟启动服务
void startService(const std::string &id)
{
    for (auto &service : services)
    {
        if (service.id == id)
        {
            service.status = ServiceStatus::Starting;
            service.lastUpdated = getCurrentTime();

            // 模拟启动过程
            std::thread([&service]()
                        {
                std::this_thread::sleep_for(std::chrono::seconds(2));
                service.status = ServiceStatus::Running;
                service.lastUpdated = getCurrentTime(); })
                .detach();
            break;
        }
    }
}

// 模拟停止服务
void stopService(const std::string &id)
{
    for (auto &service : services)
    {
        if (service.id == id)
        {
            service.status = ServiceStatus::Stopping;
            service.lastUpdated = getCurrentTime();

            // 模拟停止过程
            std::thread([&service]()
                        {
                std::this_thread::sleep_for(std::chrono::seconds(2));
                service.status = ServiceStatus::Stopped;
                service.lastUpdated = getCurrentTime(); })
                .detach();
            break;
        }
    }
}

// 模拟更新服务
void updateService(const std::string &id, const std::string &name, const std::string &description)
{
    for (auto &service : services)
    {
        if (service.id == id)
        {
            service.name = name;
            service.description = description;
            service.lastUpdated = getCurrentTime();
            break;
        }
    }
}

// 模拟添加服务
void addService(const std::string &name, const std::string &description)
{
    Service newService;
    newService.id = generateId();
    newService.name = name;
    newService.description = description;
    newService.status = ServiceStatus::Stopped;
    newService.lastUpdated = getCurrentTime();
    services.push_back(newService);
}

// 模拟删除服务
void removeService(const std::string &id)
{
    services.erase(
        std::remove_if(services.begin(), services.end(),
                       [id](const Service &service)
                       { return service.id == id; }),
        services.end());
}

int main()
{
    Server svr;

    // 静态文件服务
    svr.set_base_dir("./www");

    // API端点：获取服务列表
    svr.Get("/api/services", [](const Request &, Response &res)
            {
        json servicesJson;
        for (const auto& service : services) {
            servicesJson.push_back(serviceToJson(service));
        }
        res.set_content(servicesJson.dump(), "application/json"); });

    // API端点：启动服务
    svr.Post(R"(/api/services/(\w+)/start)", [](const Request &req, Response &res)
             {
        auto id = req.matches[1];
        startService(id);
        res.status = 200; });

    // API端点：停止服务
    svr.Post(R"(/api/services/(\w+)/stop)", [](const Request &req, Response &res)
             {
        auto id = req.matches[1];
        stopService(id);
        res.status = 200; });

    // API端点：更新服务
    svr.Post(R"(/api/services/(\w+)/update)", [](const Request &req, Response &res)
             {
        auto id = req.matches[1];
        auto name = req.get_param_value("name");
        auto description = req.get_param_value("description");
        updateService(id, name, description);
        res.status = 200; });

    // API端点：添加服务
    svr.Post("/api/services/add", [](const Request &req, Response &res)
             {
        auto name = req.get_param_value("name");
        auto description = req.get_param_value("description");
        addService(name, description);
        res.status = 200; });

    // API端点：删除服务
    svr.Post(R"(/api/services/(\w+)/remove)", [](const Request &req, Response &res)
             {
        auto id = req.matches[1];
        removeService(id);
        res.status = 200; });

    std::cout << "Server started on port 8080..." << std::endl;
    svr.listen("localhost", 8080);

    return 0;
}
